<?php
/**
 * @Author: rocky
 * Date: 2019/10/8
 * Time: 15:41
 */


namespace app\shop\controller\api\v1;


use app\common\controller\BaseApiController;
use app\common\facade\Token;
use app\shop\model\ShopOrder;
use app\shop\model\ShopOrderGoods;
use app\shop\model\ShopOrderRefund;
use app\shop\model\ShopRefundGood;
use app\common\model\ShopOrderTip;
use app\shop\resource\OrderGoodResoure;
use app\shop\resource\OrderResoure;
use app\shop\resource\RefundListResoure;
use app\shop\validate\RefundChangeValidate;
use app\shop\validate\RefundValidate;
use think\Db;
use think\db\Query;
use think\Exception;

/**
 * 订单售后
 * Class OrderRefund
 * @package app\shop\controller\api\v1
 */
class OrderRefund extends BaseApiController
{
    /*
     * 提交申请售后
     */
    public function postApply()
    {
        $post = (new RefundValidate())->goCheck();
        $order = ShopOrder::uid()->where('type', 1)->where(function (Query $q) {
            $q->whereTime('complete_time', '>=', time() - sysconf('order_refund_time') * 3600 * 24)->whereNull('complete_time', 'OR');
        })->where('status', '=', 2)->find($post['order_id']);
        if (!$order) {
            $this->errorCode(100, '订单不允许售后或不存在');
        }
        $refund = ShopOrderRefund::where('order_id', $post['order_id'])->where('status', '>', 0)->where('status', '<>', 3)->find();
        if ($refund) {
            $this->errorCode(100, '订单已经申请售后');
        }
        $goods = ShopOrderGoods::where('order_id', $post['order_id'])->select();
        if ($goods->isEmpty()) {
            $this->errorCode(100, '申请售后商品不存在');
        }
        $price = 0;
        if ($post['type'] == 1) {
            foreach ($goods as $good) {
                $price += $good['price'] * $good['num'];
            }
        }
        $post['store_id'] = $order['store_id'];
        $post['price'] = $price;
        $post['uid'] = Token::id();
        Db::startTrans();
        try {
            $refund = ShopOrderRefund::create($post);
            $refund_goods = [];
            foreach ($goods as $good) {
                $refund_goods[] = [
                    'order_good_id' => $good['id'],
                    'refund_id' => $refund['id']
                ];
            }
            (new ShopRefundGood())->saveAll($refund_goods);
            $data = [
                'order_id' => $post['order_id'],
                'uid' => $order['uid'],
                'title' => '预约已取消',
                'content' => '预约订单已取消，系统审核通过后将为您退款'
            ];
            //取消预约将status改为7（取消预约）
            // $order = model('ShopOrder')->where('order_no',$data['out_trade_no'])->find();
            $update_status= model('ShopOrder')->where('id',$order['id'])->find();
            $update_status->status = '7';
            $update_status->save();
            // Db::table('think_user')->where('id', 1)->update(['name' => 'thinkphp']);
            ShopOrderTip::create($data);
            Db::commit();
            $this->successCode();
        } catch (Exception $e) {
            Db::rollback();
            $this->errorCode();
        }
    }

    /*
     * 售后订单列表
     */
    public function getInfo()
    {
        $data = ShopOrderRefund::uid()->pages()->with(['order','order.store'])->select();
        $this->successCode(RefundListResoure::collection($data));
    }

    /*
     * 售后订单详情
     */
    public function getDetail()
    {
        $refund = ShopOrderRefund::uid()->with(['order.good', 'good'])->find($this->request->id);

        if (empty($refund)) {
            $this->errorCode(100, '售后订单不存在');
        }
        $data['order'] = OrderResoure::item($refund['order']);
        $data['refund_good'] = OrderGoodResoure::collection($refund['good']);
        $data['refund'] = $refund->hidden(['order', 'good']);
        $this->successCode($data);
    }

    /*
     * 填写换货信息(用户寄回)
     */
    public function putChange()
    {
        $data = (new RefundChangeValidate())->goCheck();
        $refund = ShopOrderRefund::uid()->where('type', 2)->where('status', 2)->find($data['id']);
        if (empty($refund)) {
            $this->errorCode(100, '售后订单无效');
        }
        $data['status'] = 3;
        ShopOrderRefund::update($data);
        $this->successCode();
    }

    /*
     * 取消售后
     */
    public function putCancel()
    {
        $refund = ShopOrderRefund::uid()->where('status', 1)->find($this->request->id);
        if (empty($refund)) {
            $this->errorCode(100, '售后订单无效');
        }
        $refund->status = -1;
        $refund->save();
        $this->successCode();
    }
}